/**
 * create by young (young2f@outlook.com) on 2023/4/16
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const _stringUtils = require('../utils/stringUtils');
const moment = require('moment');
module.exports = class extends base {
    async findMany(body) {
        console.log('find meter Many body', body);
        delete body.tenantCode;
        const {deviceId, deviceName} = body;
        if (deviceId) body['deviceId'] = {$regex: deviceId};
        if (deviceName) body['deviceName'] = {$regex: deviceName};
        const sort = {};
        sort['time'] = -1;
        const result = await this.app.dbs.find('PowerMeter', body, sort);
        console.log('find meter Many', result);
        return {status: 'ok', result};
    }

    async findDayPower(body) {
        const {ctx} = this;
        //   console.log('find meter Many body', body);
        //delete body.tenantCode;
        const {day, tenantCode} = body;
        const time = getInitTime();

        body['time'] = {
            $gte: time.start,
            $lt: time.end
        };
        delete body.day;
        console.log('find meter Many body', body);
        const sort = {};
        sort['time'] = 1;
        const list = await this.app.dbs.find('IotDevice', {tenantCode, deviceType:{$regex: "智能电表"}});
        const deviceIds = {};
        _.map(list, item => {
            const {deviceName, deviceId} = item;
            deviceIds[deviceId] = ({name: deviceName});
        });
        const _day = moment(day).format('YYYY-MM-DD') + " 00:00:00";
        for (let i = 0; i < 24; i++) {
            const value = moment(_day).add(1 * i, "hours").format("YYYY-MM-DD HH:mm:ss");
            const arr = await this.app.dbs.find('PowerMeterDay', {tenantCode, timeStr: value});
            _.map(deviceIds, (v, k) => {
                const temp = _.find(arr, item => item.deviceId === k);
                v[moment(value).hour() + "hour"] = temp ? temp.value : 0;
            });
        }

        const result = [];
        _.map(deviceIds, (v, k) => {
            result.push(v);
        });
        result.reverse();
        return {status: 'ok', result};
    }

    async exportExcel(body) {
        const {ctx} = this;

        delete body.tenantCode;
        const {day} = body;
        const time = getInitTime();

        body['time'] = {
            $gte: time.start,
            $lt: time.end
        };
        delete body.day;
        //   console.log('find meter Many body', body);
        const sort = {};
        sort['time'] = 1;
        const list = await this.app.dbs.find('IotDevice', {deviceType:{$regex: "智能电表"}});
        // console.log('find meter Many', list);

        const deviceIds = {};
        const header = [];

        header.push({title: "电表名称", key: "name"});
        for (let i = 0; i < 24; i++) {
            header.push({title: i + "时", key: i + "hour"});
        }
        _.map(list, item => {
            const {deviceName, deviceId} = item;
            deviceIds[deviceId] = ({name: deviceName});
        });

        const _day = moment(day).format('YYYY-MM-DD') + " 00:00:00";
        for (let i = 0; i < 24; i++) {
            const value = moment(_day).add(1 * i, "hours").format("YYYY-MM-DD HH:mm:ss");
            //   console.log('find meter Many', value);
            const arr = await this.app.dbs.find('PowerMeterDay', {"timeStr": value});
            // const arr = await this.app.dbs.find('PowerMeter', {deviceId:"F5Meter"});
            // console.log('find meter Many list', arr);
            _.map(deviceIds, (v, k) => {
                const temp = _.find(arr, item => item.deviceId === k);
                v[moment(value).hour() + "hour"] = temp ? temp.value : 0;
            });
        }
        // console.log('find meter Many', deviceIds);
        const data = [];
        _.map(deviceIds, (v, k) => {
            data.push(v);
        });
        return {status: 'ok', result: {header, data}};
    }

    async findBindingDeviceMany(body) {
        const {ctx} = this;
        //   console.log('find meter Many body', body);
        //delete body.tenantCode;
        const {day, tenantCode, powerTreeId} = body;
        const time = getInitTime();

        body['time'] = {
            $gte: time.start,
            $lt: time.end
        };
        delete body.day;
        console.log('find meter Many body', body);
        const sort = {};
        sort['time'] = 1;
        const list = await this.app.dbs.find('IotDevice', {tenantCode, powerTreeId, deviceType:{$regex: "智能电表"}});
        const deviceIds = {};
        _.map(list, item => {
            const {deviceName, deviceId} = item;
            deviceIds[deviceId] = ({name: deviceName});
        });
        const _day = moment(day).format('YYYY-MM-DD') + " 00:00:00";
        let totalAssess = 0;
        for (let i = 0; i < 24; i++) {
            const value = moment(_day).add(1 * i, "hours").format("YYYY-MM-DD HH:mm:ss");
            const arr = await this.app.dbs.find('PowerMeterDay', {tenantCode, timeStr: value});
            _.map(deviceIds, (v, k) => {
                const temp = _.find(arr, item => item.deviceId === k);
                const _v = temp ? temp.value : 0;
                v[moment(value).hour() + "hour"] = _v;
                totalAssess += _v;
            });
        }

        const meters = [];
        _.map(deviceIds, (v, k) => {
            meters.push(v);
        });
        meters.reverse();
        const totalJson = {name: '合计'};

        for (let i = 0; i < 24; i++) {
            let num = 0;
            const value = moment(_day).add(1 * i, "hours").format("YYYY-MM-DD HH:mm:ss");
            const key = moment(value).hour() + "hour";
            _.map(meters, (meter) => {
                console.log('find meter Many meter', JSON.stringify(meter));

                num += meter[key];
            });

            totalJson[key] = num;

        }
        meters.push(totalJson);
        return {status: 'ok', result: {meters, assess: {totalAssess}}};
    }
};

// 获取指定时间零点
// num几天前
const getInitTime = (day) => {
    let start = moment(new Date(moment(day).valueOf())).startOf("day"); // 00:00
    let end = moment(new Date(moment(day).valueOf())).endOf("day"); //23:59
    // return moment(today).subtract(num, "day").format("YYYY-MM-DD HH:mm");
    return {start, end};
};


